import { 
    setTokenKey, 
    setRefreshTokenKey, 
    setUsernameKey, 
    setDepartmentKey,
    logout, 
    login } from "../Type";
// 方法
import { 
    setToken, 
    setRefreshToken, 
    setUsername, 
    setDepartment,
    removeToken, 
    removeUsername,
    removeRefreshToken,
    removeDepartment } from "@/utils/cookies";
// API
import { Login } from "../../api/account";

export function setTokenAction(data){
    setToken(data);
    return {
        type: setTokenKey,
        value: data
    }
}

export function setRefreshTokenAction(data){
    setRefreshToken(data);
    return {
        type: setRefreshTokenKey,
        value: data
    }
}
            
export function setUsernameAction(data){
    console.log(data)
    setUsername(data);
    return {
        type: setUsernameKey,
        value: data
    }
}

export function setDepartmentAction(data){
    console.log(data)
    setDepartment(data);
    return {
        type: setDepartmentKey,
        value: data
    }
}

export function logoutAction(){
    removeToken();
    removeUsername();
    removeRefreshToken();
    removeDepartment();
    return {
        type: logout,
        value: ""
    }
}

// 登录逻辑
export const accountLoginAction = (data) => dispatch => {
    return dispatch({
        type: login,
        payload: new Promise((resolve, reject) => {
            Login(data).then(response => {
                const data = response.data.data;
                dispatch(setTokenAction(data.access_token));
                dispatch(setRefreshTokenAction(data.refresh_token));
                dispatch(setUsernameAction(data.username));
                dispatch(setDepartmentAction(data.department));
                resolve();
            }).catch(error => {
                reject(error);
            })
        })
    })
}